import salePlanApi from "../../../common/api/breedsales/planbills.api.js"
import WxcodeApi from '../../../common/api/account/wxcode.api.js'
import { DictionaryType, requestDict } from "../../../common/dictionary/dictionary-type.js";
import { uploadFile, requestFilePath, publicFileDraw, sliceFileName } from "../../../common/api/file-request.js";
import { Select2Page } from "../../../common/serve-request.js";

(function (window, document, $) {
    $('body').attr('data-weui-theme', 'light'); //强制光明模式

    var _vm = new Vue({
        el: '#vehicle-app',
        data() {
            return {
                saleOrgList: [],
                farmOrgList: [],
                pigTypeList: [],
                saleOrgDisabled: false,
                farmOrgDisabled: false,
                breedBatchDisabled: false,
                isUploading: false,
                showDatePicker: false,
                form: {
                    saleOrgId: '',
                    saleOrgName: '',
                    farmOrgId: '',
                    farmOrgName: '',
                    breedBatchId: '',
                    breedBatchName: '',
                    bizDate: '',
                    entryDate: '',
                    count: '',
                    pigDays: '',
                    pigType: '',
                    avgWeight: '',
                    difference: '',
                    remark: '',
                    attachList: []
                },
                orginForm: {}
            }
        },
        watch: {
            'form.saleOrgId': {
                handler(nVal) {
                    if (nVal) {
                        this.initFarmselect(nVal)
                        if (!this.form.id) {
                            this.farmOrgDisabled = false
                        }
                        $(`#breedBatchId`).val('').trigger('change')
                    }
                }
            },
            'form.farmOrgId': {
                handler(nVal) {
                    if (nVal) {
                        this.initBreedBatchSelect(nVal)
                        this.breedBatchDisabled = false
                    }
                }
            }
        },
        async created() {
            this.form.bizDate = moment().format('YYYY-MM-DD')
            this.initForm()
            // 获取正负差
            salePlanApi.getDifference('LIVESTOCK-SALE-DIFF').then(res => {
                this.form.difference = `±${res}`
            })
        },
        mounted() {
            this.initUpload()
            this.initGallery()
            let url = location.href
            let params = {} // url参数
            for (let key of (new URL(url)).searchParams.entries()) {
                key[1] ? params[key[0]] = key[1] : ''
            }
            if (params.id) {
                document.title = '销售计划 - 编辑'
                this.farmOrgDisabled = true
                this.saleOrgDisabled = true
                this.form.id = params.id
                this.getDetail(params.id)
            }
        },
        methods: {
            async getDetail(id) {
                await salePlanApi.getSalePlanDetail({ id }).then(async res => {
                    res.attachList = []
                    res.bizDate = moment(res.bizDate).format('YYYY-MM-DD')
                    res.entryDate = moment(res.entryDate).format('YYYY-MM-DD')
                    res.difference = `±${res.difference}`
                    this.form = res
                    this.orginForm = JSON.parse(JSON.stringify(res))
                    if (Utils.IsNotNull(res.attaches)) {
                        let attachList = res.attaches.split(',')
                        for (let i = 0; i < attachList.length; i++) {
                            await requestFilePath(attachList[i]).then(res => {
                                this.form.attachList.push({ imageId: attachList[i], url: res.data })
                                let _li = `<li class="weui-uploader__file" data-url="${res.data}" style="background-image: url(${res.data}) "></li>`
                                $('#uploaderFiles').append(_li);
                            })
                        }
                    }
                    this.$nextTick(() => {
                        setTimeout(() => {
                            $(`#farmOrgId`).val(this.orginForm.farmOrgId).trigger('change')
                            $(`#saleOrgId`).val(this.orginForm.saleOrgId).trigger('change')
                            let option = new Option(this.orginForm.breedBatchName, this.orginForm.breedBatchId, false, false)
                            $(`#breedBatchId`).append(option).trigger('change');
                            $(`#breedBatchId`).val(this.orginForm.breedBatchId).trigger('change')
                            $(`#pigType`).val(this.orginForm.pigType).trigger('change')
                        }, 200);
                    })
                })
            },
            async initForm() {
                this.$nextTick(() => {
                    // 初始化农场
                    $(`#farmOrgId`).select2({
                        placeholder: '请选择农场...', //默认文字提示
                        language: "zh-CN",//汉化
                        data: []
                    })
                    $(`#farmOrgId`).on('change', function (e, a) {
                        that.form.farmOrgId = $(this).val() || ''
                        that.form.farmOrgName = $(this).select2('data')[0]?.name || ''
                    })
                    $(`#farmOrgId`).val(this.form.farmOrgId || '').trigger('change')

                    // 初始化养殖批次 分页
                    $(`#breedBatchId`).select2({
                        placeholder: '请选择批次...', //默认文字提示
                        language: "zh-CN",//汉化
                        data: []
                    })
                    $(`#breedBatchId`).val(this.form.breedBatchId || '').trigger('change')
                    $(`#breedBatchId`).on('change', function (e, a) {
                        that.form.breedBatchId = $(this).val()
                        that.form.breedBatchName = $(this).select2('data')[0]?.name || ''
                    })
                })
                let that = this
                let userInfo = JSON.parse(Utils.GetSessionStorage("SNLoginUserInfo")) || {};

                if (!Utils.IsNotNull(userInfo)) {
                    let _json = await WxcodeApi.queryUserName();
                    Utils.SetSessionStorage("SNLoginUserInfo", _json);
                    userInfo = _json
                }
                Promise.allSettled([salePlanApi.getOrgSaleList(), salePlanApi.postUserOrgsList()]).then(res => {
                    // 获取销售组织和我的所在组织,过滤得到组织
                    let allorg = res[0].value.filter(s => s.typeValue == true)
                    // let allorg = res[0].value
                    let myOrg = res[1].value
                    this.saleOrgList = myOrg.filter(item => allorg.some(item2 => item2.id == item.oId));
                    this.saleOrgList = this.saleOrgList.map(item => {
                        return { ...item, id: item.oId, text: `${item.oName}(${item.oNumCode})` }
                    })
                    let curOrg = this.saleOrgList.find(item => item.oId == userInfo.curOrgId)
                    $(`#saleOrgId`).select2({
                        placeholder: '请选择公司...', //默认文字提示
                        language: "zh-CN",//汉化
                        data: this.saleOrgList
                    })
                    $(`#saleOrgId`).on('change', function (e, a) {
                        that.form.saleOrgId = $(this).val()
                        that.form.saleOrgName = $(this).select2('data')[0]?.oName || ''
                    })
                    $(`#saleOrgId`).val(this.form.saleOrgId || curOrg?.oId || '').trigger('change')
                })

                // 销售品类
                requestDict(DictionaryType.LEVEL_TYPE).then(res => {
                    this.pigTypeList = res.data.map(item => {
                        return { ...item, id: item.value, text: item.displayName }
                    })
                    $(`#pigType`).select2({
                        placeholder: '请选择销售品类...', //默认文字提示
                        language: "zh-CN",//汉化
                        data: this.pigTypeList
                    })
                    $(`#pigType`).val(this.form.pigType || '').trigger('change')
                    $(`#pigType`).on('change', function (e, a) {
                        that.form.pigType = $(this).val()
                    })
                })
            },
            // 初始化农场选择
            initFarmselect(id) {
                salePlanApi.queryComDepList(id, 1, 210).then(res => {
                    this.farmOrgList = res.map(item => {
                        return { ...item, id: item.id, text: item.name }
                    })
                    $(`#farmOrgId`).empty().select2({
                        placeholder: '请选择农场...', //默认文字提示
                        language: "zh-CN",//汉化
                        data: this.farmOrgList
                    })
                    $(`#farmOrgId`).val(this.form.farmOrgId || '').trigger('change')
                })
            },
            // 初始化养殖批次
            initBreedBatchSelect(farmOrgId) {
                $(`#breedBatchId`).empty()
                Select2Page($(`#breedBatchId`), `${salePlanApi.getBreedbatchsListUrl}`, (params) => {
                    return JSON.stringify({
                        name: params.term,
                        pageSize: 20,
                        pageIndex: (params.pageIndex || 1) - 1,
                        farmOrgId
                    })
                }, "POST", {
                    templateResult: function (res) {
                        return `${res.name == undefined ? res.text : res.name}`;
                    },
                    placeholder: '请选择批次...'
                });
            },
            // 初始化图片预览组件
            initGallery() {
                let that = this
                $('#uploaderFiles').click(function (e) {
                    let target = e.target;
                    while (!target.classList.contains('weui-uploader__file') && target) {
                        target = target.parentNode;
                    }
                    if (!target) return;
                    //从图片对应的li标签中获得所需属性
                    let gallery = weui.gallery($(target).attr('data-url'), {
                        className: 'custom-name',
                        onDelete: function () {
                            //删除图片的回调
                            $.confirm({
                                title: '删除提示',
                                text: '确定删除该图片？',
                                onOK: function () {
                                    let _id = $(target).attr('data-id');
                                    that.form.attachList = that.form.attachList.filter(item => item.id != _id);
                                    target.remove();
                                    gallery.hide();
                                },
                                onCancel: function () {
                                }
                            });
                        }
                    });
                });
            },
            // 初始化上传组件
            initUpload() {
                let that = this
                weui.uploader('#uploader', {
                    url: '',
                    auto: false,
                    type: 'file',
                    compress: { isNoTCompress: true },
                    onBeforeQueued: function (files) {
                        // `this` 是轮询到的文件, `files` 是所有文件
                        if (["image/jpg", "image/jpeg", "image/png"].indexOf(this.type) < 0) {
                            $.toptip('请上传图片', 'warning');
                            return false; // 阻止文件添加
                        }
                        if (this.size > 8 * 1024 * 1024) {
                            $.toptip('请上传不超过8M的文件', 'warning');
                            return false;
                        }
                        $.showLoading('上传中..');
                        that.isUploading = true
                    },
                    onQueued: function () {
                        let formFile = new FormData();
                        let upFiles = this;
                        let file = publicFileDraw(this.name, _vm);
                        if (file != false && file != undefined) {
                            formFile.append('apiobjfile', new window.File([this], file, { type: this.type }));
                            that._uploadFileDraw(formFile, upFiles, _vm, file);
                        }
                        //确认提交
                        $('.weui-dialog__btn').on('click', function () {
                            if ($(this)[0].innerHTML == '确认') {
                                $.showLoading('上传中...');
                                let fileName = sliceFileName(upFiles);
                                let newfile = publicFileDraw(fileName, _vm);
                                if (newfile != false && newfile != undefined) {
                                    formFile.append('apiobjfile', new window.File([upFiles], newfile, { type: upFiles.type }));
                                    that._uploadFileDraw(formFile, upFiles, _vm, newfile);
                                }
                            }
                        });
                        return true;
                    }
                });
            },
            // 附件上传
            _uploadFileDraw(formFile, upFiles, _vm, newName) {
                uploadFile(formFile).then(res => {
                    this.isUploading = false
                    if (res.isSucceed) {
                        let item = {
                            id: $("#uploaderFiles li").length,
                            imageId: res.data,
                            url: upFiles.url,
                            name: newName,
                            type: upFiles.name.split('.').pop().toLowerCase()
                        }
                        this.form.attachList.push(item)
                        let attachList = this.form.attachList
                        // 在dom上添加图片
                        $("#uploaderFiles li").each(function (i) {
                            $(this).attr('data-id', attachList[i].id);
                            $(this).attr('data-image-id', attachList[i].imageId);
                            $(this).attr('data-name', attachList[i].name);
                            $(this).attr('data-suffix', attachList[i].type);
                            if (["jpg", "jpeg", "png", 'gif'].indexOf(attachList[i].type) < 0) {
                                $(this).attr('data-url', '../../../../public/static/images/other/pic_default_uploader.png');
                                $(this).css({ 'background-image': `url(${'../../../../public/static/images/other/pic_default_uploader.png'})` });
                            } else {
                                $(this).attr('data-url', attachList[i].url);
                                $(this).css({ 'background-image': `url(${attachList[i].url})` });
                            }
                        });
                        $('.weui-uploader__file-content').hide();
                        $('.weui-uploader__file').removeClass('weui-uploader__file_status');
                        $.hideLoading();
                        $.closeModal();
                    }
                }).catch(res => {
                    this.isUploading = false
                    $("#uploaderFiles li").eq($("#uploaderFiles li").length - 1).remove();
                    $.toptip(res.msg, 'error');
                }).finally(_ => {
                    $.hideLoading();
                    $.closeModal();
                });
            },
            // 点击日期选择
            clickDate(key) {
                let that = this
                that.showDatePicker = true
                let now = moment().format('YYYY-MM-DD')
                let options = {
                    defaultValue: now.split('-')
                }
                if (key === 'bizDate') {
                    options.end = moment(now).add(1, 'w').format('YYYY-MM-DD')
                }
                if (this.form[key]) {
                    options.defaultValue = moment(this.form[key]).format('YYYY-MM-DD').split('-')
                }
                weui.datePicker({
                    ...options,
                    container: 'body',
                    onConfirm: function (result) {
                        //let a = result.map(item => item.value).join('-')
                        that.form[key] = result.map(item => item.value).join('-')
                        that.showDatePicker = false
                    },
                    onClose: function () {
                        that.showDatePicker = false
                    },
                    id: moment().valueOf() // 每次传入不同id,保证defaultValue刷新
                });
            },
            validateForm() {
                return new Promise((resolve, reject) => {
                    let { saleOrgId, farmOrgId, breedBatchId, bizDate, entryDate, pigType, count, pigDays, avgWeight, difference } = this.form
                    let emptyMsg = {
                        saleOrgId: '请选择公司',
                        farmOrgId: '请选择农场',
                        breedBatchId: '请选择批次',
                        bizDate: '请选择业务日期',
                        entryDate: '请选择入群日期',
                        pigType: '请选择销售品类',
                        count: '请输入数量',
                        pigDays: '请输入日龄',
                        avgWeight: '请输入均重',
                        difference: '请输入正负差',
                    }
                    for (let key in emptyMsg) {
                        if (!String(this.form[key]) || String(this.form[key]) === 'null') {
                            return reject(emptyMsg[key])
                        }
                    }
                    const reg = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/
                    const numReg = /^\d+$/
                    if (!String(count).match(numReg)) {
                        return reject('数量只能输入正整数')
                    }
                    if (!(/(^[1-9]\d*$)/.test(count))) {
                        return $.toptip(`数量必须大于0!`, 'warning');
                    }
                    if (!String(pigDays).match(numReg)) {
                        return reject('日龄只能输入正整数')
                    }
                    if (!(/(^[1-9]\d*$)/.test(pigDays))) {
                        return $.toptip(`日龄必须大于0!`, 'warning');
                    }
                    if (!String(avgWeight).match(reg)) {
                        return reject('均重必须大于0且小数点后最多为两位')
                    }
                    return resolve(true)
                })
            },
            submit() {
                this.validateForm().then(res => {
                    let params = this.form
                    params.attaches = params.attachList.map(item => item.imageId).join(',')
                    params.breedBatchName = params.breedBatchName || this.orginForm.breedBatchName
                    params.difference = params.difference.split('±')[1];
                    let promise = null
                    if (this.form.id) {
                        promise = salePlanApi.updateSalePlan(params)
                    } else {
                        promise = salePlanApi.addSalePlan(params)
                    }
                    promise.then(res => {
                        $.toptip('保存成功', 'success');
                        location.href = './saleplanlist.html'
                    })
                })
                    .catch(err => {
                        $.toptip(err, 'warning');
                    })
            },
            // 返回列表
            returnList() {
                location.href = './saleplanlist.html'
            }
        }
    })

})(window, document, jQuery)